import { useState } from 'react';
import {
    DesktopOutlined,
    FileOutlined,
    PieChartOutlined,
    UserOutlined,
} from '@ant-design/icons';
import { Menu } from 'antd';
import type { MenuProps } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';

type MenuItem = Required<MenuProps>['items'][number];

const items: MenuItem[] = [
    {
        label: '预定情况',
        key: '/bookingData',
        icon: <PieChartOutlined />
    },
    {
        label: '入住情况',
        key: '/Room',
        icon: <DesktopOutlined />
    },
    {
        label: '客户管理',
        key: 'customer',
        icon: <UserOutlined />,
        children: [
            {
                label: '已入住客户',
                key: '/customer/data',
            }
        ]
    },
    {
        label: '账单',
        key: '/bill',
        icon: <FileOutlined />
    }
]

const Comp = () => {
    const navigateTo = useNavigate();
    const { pathname } = useLocation(); //useLocation获取当前路由信息

    const menuClick = (e: { key: string }) => {
        navigateTo(e.key);
    }

    let firstOpenKey:string = ""
    //在这里进行比较
    const findKey = (obj:{key:string}) => obj.key === pathname
    for(let i = 0; i < items.length; i++){
        //items[i]!['children'].find(findKey)  这结果如果找到拿到的，就是找到的这个对象，转布尔值就是true。如果找不到就是false
        //  ! --- 用来肯定items[i]的值是有的
        if(items[i]!['children'] && items[i]!['children'].length > 0 && items[i]!['children'].find(findKey)){
            firstOpenKey = items[i]!.key as string
            break;
        }
    }

    //设置展开项的初始值
    const [openKeys, setOpenKeys] = useState([firstOpenKey]);
    const handleOpenChange = (keys: string[]) => {
        // 把这个数组修改成最后一项，因为只要一项是展开的，就是我刚刚点击的这一项
        setOpenKeys([keys[keys.length - 1]])
    }
    return (
        <Menu
            theme="dark"
            defaultSelectedKeys={[pathname]} //表示当前样式所在的选项中的key
            mode="inline"
            items={items}
            onClick={menuClick}
            // 某项菜单展开和回收的事件
            onOpenChange={handleOpenChange}
            openKeys={openKeys}
        />
    )
}

export default Comp